<?php


namespace app\common\model\user;

use app\common\model\BaseModel;
use app\common\library\qcloudsms\SmsSingleSender;

/**
 * 短信模型
 */
class TxSms extends BaseModel
{
    protected $pk = 'sms_id';
    protected $name = 'sms';

    /**
     * 短信发送
     */
    public function send($mobile, $sence = 'login')
    {
        if (empty($mobile)) {
            $this->error = lang('smscode.mobileEmpty');
            return false;
        }
        if ($sence == 'login') {//登录
            $templateId = "1576326";
        } else if ($sence == 'register') {//注册
            $templateId = "1576326";
            //判断是否已经注册
            $user = (new User)->where('mobile', '=', $mobile)->find();
            if ($user) {
                $this->error = '手机号码已存在';
                return false;
            }
        } else if ($sence == 'reset') {//重置密码
            $templateId = "1576340";
            //判断是否存在
            $user = (new User)->where('mobile', '=', $mobile)->count();
            if (!$user) {
                $this->error = lang('smscode.mobileNoExist');
                return false;
            }
        } else {
            return false;
        }
        $code = str_pad(mt_rand(100000, 999999), 6, "0", STR_PAD_BOTH);
        //短信模板
        $flag = $this->sendSms($mobile, $code, $templateId);
        if ($flag) {
            $this->save([
                'mobile' => $mobile,
                'code' => $code,
                'app_id' => self::$app_id
            ]);
        }
        return $flag;
    }

    public function sendSms($phone, $code, $templateId)
    {
        if (empty($phone) || empty($code)) {
            return false;
        }
        $appid = "1400749102";
        $appkey = "72add0f3b44a22297402bfea492fb186";
        $smsSign = "北京健恩";
        try {
            $ssender = new SmsSingleSender($appid, $appkey);
            $params = ["{$code}"];
            $result = $ssender->sendWithParam("86", $phone, $templateId,
                $params, $smsSign, "", "");
            $rsp = json_decode($result, 1);
            if ($rsp['result'] == 0) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }
}